// src/image/image.controller.ts
import {
  Controller,
  Get,
  Post,
  Query,
  Body,
  UploadedFile,
  UseInterceptors
} from '@nestjs/common';
import { FileInterceptor } from '@nestjs/platform-express';
import { ApiConsumes, ApiOperation } from '@nestjs/swagger';
import { ImageService } from './image.service';
import { CreateImageDto } from './dto/create-image.dto';
import { ImageEntity } from './entities/image.entity';
import { diskStorage } from 'multer';
import { extname } from 'path';

@Controller('image')
export class ImageController {
  constructor(private imageService: ImageService) {}

  @ApiOperation({ summary: '分页获取图片列表（瀑布流）' })
  @Get('list')
  getImageList(
    @Query('page') page = 1,
    @Query('pageSize') pageSize = 30
  ): Promise<{ total: number; list: ImageEntity[] }> {
    return this.imageService.getPaginatedList(+page, +pageSize);
  }

  @ApiOperation({ summary: '上传图片文件' })
  @ApiConsumes('multipart/form-data')
  @Post('upload')
  @UseInterceptors(
    FileInterceptor('file', {
      storage: diskStorage({
        destination: './uploads',
        filename: (_req, file, cb) => {
          const uniqueSuffix = Date.now() + '-' + Math.round(Math.random() * 1e9);
          const ext = extname(file.originalname);
          cb(null, `${uniqueSuffix}${ext}`);
        }
      })
    })
  )
  async uploadImage(@UploadedFile() file: Express.Multer.File): Promise<ImageEntity> {
    return this.imageService.handleUpload(file);
  }

  @ApiOperation({ summary: '创建图片数据（通过src链接）' })
  @Post()
  create(@Body() dto: CreateImageDto): Promise<ImageEntity> {
    return this.imageService.create(dto);
  }
}
